<template>
<div class="toutiao-applets-channel views-container">
    <choose-files ref="chooseFilesIcon" :config="chooseFilesConfig" :changeEvt="uploadChange"></choose-files>
    <choose-link ref="chooseIconLink" :config="chooseIconLinkConfig" :changeEvt="uploadIconFileChange"></choose-link>
    <div class="wlm-table">
        <div class="warning">
            <div class="flex-row flex-justify-b flex-align-c">
                <div>
                    <p class="warning-title">头条小程序</p>
                    <p style="margin-top:10px;">绑定头条小程序，将平台与头条小程序打通</p>
                </div>
                <div>
                    <el-button style="margin-right:20px;" v-if="!isOpenEdit" size="small" plain class="orders-blue" @click="open">修改配置</el-button>
                    <el-switch v-model="formFormatData.formData.channel.toutiao.switch" @change="switchChannel" active-value="1" inactive-value="0">
                    </el-switch>
                </div>
            </div>
        </div>
        <div class="flex-row flex-warp">
            <div class="wlm-form" style="width:50%">
                <section>
                    <div class="wlm-form-content channel-card">
                        <el-form v-if="formFormatData.isOpendSetting" :ref="formFormatData.key" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="140px" class="retail-form" label-position="right">
                            <el-form-item label="小程序名称" prop="username">
                                <span v-if="!isOpenEdit">{{formFormatData.formData.channel.toutiao.name}}</span>
                                <el-input v-if="isOpenEdit" v-model="formFormatData.formData.channel.toutiao.name"></el-input>
                            </el-form-item>
                            <el-form-item label="AppId" prop="password">
                                <span v-if="!isOpenEdit">{{formFormatData.formData.channel.toutiao.AppId}}</span>
                                <el-input v-if="isOpenEdit" v-model="formFormatData.formData.channel.toutiao.AppId"></el-input>
                            </el-form-item>
                            <el-form-item label="AppSecret" prop="repassword">
                                <span v-if="!isOpenEdit">{{formFormatData.formData.channel.toutiao.AppSecret}}</span>
                                <el-input v-if="isOpenEdit" v-model="formFormatData.formData.channel.toutiao.AppSecret"></el-input>
                            </el-form-item>
                            <el-form-item label="小程序LOGO" prop="repassword">
                                <img v-if="!isOpenEdit" class="wlm-upload-img" :src="formFormatData.formData.channel.toutiao.logo?formFormatData.formData.channel.toutiao.logo[0].file_path:`${require('@/assets/custorm_style/default_picture.png')}`">
                                <choose-files v-if="isOpenEdit" ref="chooseFiles" :config="chooseLogoConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                                <div class="form-help">建议尺寸：100*100px</div>
                            </el-form-item>
                            <el-form-item label="二维码" prop="repassword" class="slider">
                                <img v-if="!isOpenEdit" class="wlm-upload-img" :src="formFormatData.formData.channel.toutiao.qrcode?formFormatData.formData.channel.toutiao.qrcode[0].file_path:`${require('@/assets/custorm_style/default_picture.png')}`">
                                <choose-files v-if="isOpenEdit" ref="chooseFiles" :config="chooseBgConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                                <div class="form-help">建议尺寸：100*100px</div>
                            </el-form-item>
                              <el-form-item label="获取手机号方式" prop="repassword" class="slider">
                                    <el-radio-group v-model="formFormatData.formData.channel.toutiao.tt_bind_phone_type">
                                      <el-radio label="sms">短信</el-radio>
                                      <el-radio label="api">程序授权</el-radio>
                                    </el-radio-group>
                                    <div class="form-help">注：程序授权需要小程序获得该权限，若没有该权限请选择短信方式</div>
                            </el-form-item>
                              <el-form-item v-if="formFormatData.formData.channel.toutiao.video_entry !== undefined" label="拍视频入口" prop="repassword" class="slider">
                                   <el-checkbox-group v-model="formFormatData.formData.channel.toutiao.video_entry">
                                      <el-checkbox label="index">首页</el-checkbox>
                                      <el-checkbox label="goods">商品详情</el-checkbox>
                                    </el-checkbox-group>
                              </el-form-item>
                        </el-form>
                        <div v-else class="status-main pos-center">
                            <!-- <div class="flex-row flex-justify-b">
                            <div class="status-main-title orders-green">开通H5渠道，自动生成h5页面 <el-tag type="info">未授权</el-tag>
                            </div>
                            <router-link tag="span" to="/user/managementUser">
                                <el-button type="text" size="small" class="orders-red">编辑</el-button>
                            </router-link>
                        </div> -->
                            <!-- <p class="status-main-title">暂未接入，请先接入您的小程序</p> -->
                            <div class="flex-row flex-justify-c">
                                <div class="flex-col">
                                    <router-link tag="span" to="/channel/toutiaoAppletsChannelAdd">
                                        <el-button class="status-main-btn" type="success" style="background:rgb(104, 211, 135);border:none;"><i>
                                                <svg-icon class="status-main-svg" icon-class="ortherApplets" /></i>&nbsp; 立即接入</el-button>
                                    </router-link>
                                    <div class="flex-row flex-justify-e mar-top-4">
                                        <div>没有小程序，去<a target="_blank" href="https://mp.weixin.qq.com/" class="alink-blue">注册</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            </div>
            <div class="wlm-form" style="width:50%">
                <section>
                    <div class="wlm-form-content channel-card flex-row flex-align-c flex-justify-c">
                        <el-form v-if="formFormatData.isOpendSetting" :ref="formFormatData.key" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="1px" class="retail-form" label-position="right">
                            <el-form-item style="width:500px">
                                <div class="flex-col flex-align-c flex-justify-c">
                                    <svg-icon icon-class="toutiao" style="font-size:64px;fill:#239bff" />
                                    <p style="margin:15px 0">头条小程序</p>
                                    <el-button plain icon="document" :data-query="JSON.stringify({type:'toutiaoapp'})" v-exceldown="{path:'AppleApLetDownload&',query: {}}">代码打包下载</el-button>

                                </div>
                            </el-form-item>
                        </el-form>
                    </div>
                </section>
            </div>
        </div>
    <div class="wlm-form" >
        <div class="wlm-form-header flex-row">
        商品详情左下角操作设置
        <el-button v-if="!independent" :data-query="JSON.stringify({type:'icon'})" style="margin-left:20px" size="mini" plain icon="document" v-exceldown="{path:'',query: {},redirect: `${orga}/addons/weliam_areashop/web/assets/common/image/icon.zip?`}">下载默认图标</el-button>
        <el-button v-if="independent" :data-query="JSON.stringify({type:'icon'})" style="margin-left:20px" size="mini" plain icon="document" v-exceldown="{path:'',query: {},redirect: `${orga}/web/assets/common/image/icon.zip?`}">下载默认图标</el-button>
         <div class="form-help" style="margin-left:20px;">图标建议尺寸：100*100</div>
      </div>
      <div class="wlm-form-content">
        <el-form ref="platform" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="180px" class="retail-form" label-position="right">
          <div class="fileItemHeader flex-row flex-align-c">
            <p class="icon">图标</p>
            <p class="text">自定义文字</p>
            <p class="link">自定义链接</p>
          </div>
          <div v-for="(saveitem, saveindex) in formFormatData.formData.channel.toutiao.button" v-dragging="{ item: saveitem, list: formFormatData.formData.channel.toutiao.button, group: 'buttonLis'}" v-bind:key="saveindex" class="fileItem flex-row flex-align-c flex-justify-b">
            <div class="flex-row flex-align-c">
              <p class="fileName">{{saveitem.title}}</p>
              <img class="update-load" v-if="saveitem.image" :src="saveitem.image.file_path" width="50" height="50" @click="uploadColumn(saveindex)" />
              <div v-else class="flex-row flex-align-c flex-justify-c update-load" @click="uploadColumn(saveindex)">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <el-input style="margin:0 16px;" v-model="saveitem.input"></el-input>
              <el-radio-group v-model="saveitem.type">
                <el-radio label="1">客服</el-radio>
                <el-radio label="2">拨号</el-radio>
                <el-radio label="3">链接</el-radio>
                <el-radio label="4">分享</el-radio>
                <el-radio label="5">分享赚</el-radio>
              </el-radio-group>
              <div v-if="saveitem.type=='3'" class="link-box" @click="uploadFileToggle(saveindex)">{{saveitem.link}}</div>
            </div>
            <div>
              <i style="margin-right:20px;cursor: pointer;" class="el-icon-rank"></i>
            </div>
          </div>
        </el-form>
      </div>
    </div>
       <el-form v-if="formFormatData.isOpendSetting" :ref="formFormatData.key" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="230px" class="retail-form" label-position="right">
                            <el-form-item label="是否开启分销" prop="username">
                                <el-radio-group v-model="formFormatData.formData.channel.toutiao.is_distribution">
                                      <el-radio label="1">开启</el-radio>
                                      <el-radio label="2">关闭</el-radio>
                                    </el-radio-group>
                            </el-form-item>
                              <el-form-item label="是否开启会员卡" prop="username">
                                <el-radio-group v-model="formFormatData.formData.channel.toutiao.is_membership">
                                      <el-radio label="1">开启</el-radio>
                                      <el-radio label="2">关闭</el-radio>
                                    </el-radio-group>
                            </el-form-item>
                             <el-form-item label="商品详情是否开启'邀请他们一起逛'" prop="username" >
                                <el-radio-group v-model="formFormatData.formData.channel.toutiao.is_together" >
                                      <el-radio label="1">开启</el-radio>
                                      <el-radio label="2">关闭</el-radio>
                                    </el-radio-group>
                            </el-form-item>
                             

                            
       </el-form>
        <div class="wlm-form" >
              <div class="wlm-form-header flex-row">
                支付回调信息配置
              </div>
               <section>
                  <el-form style="margin-top:20px;width:50%;" :ref="formFormatData.key" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="230px" class="retail-form" label-position="right">
                              <el-form-item label="支付模式" prop="username" >
                                   <el-radio-group v-model="formFormatData.formData.channel.toutiao.service" >
                                      <el-radio label="1">收银台模式</el-radio>
                                      <el-radio label="5">担保交易</el-radio>
                                    </el-radio-group>
                            </el-form-item>
                            <el-form-item label="URL(服务器地址)" prop="username" v-if="formFormatData.formData.channel.toutiao.service=='5'">
                                  <!-- <el-input v-model="formFormatData.formData.channel.toutiao.tt_url" placeholder="请输入URL(服务器地址)"></el-input> -->
                                <span style="margin-left:0;" class="pointer" @click="handleClipboard(formFormatData.formData.channel.toutiao.tt_url.replace(/amp;/g,''),$event)">{{formFormatData.formData.channel.toutiao.tt_url.replace(/amp;/g,'')}}</span>
                                <p v-if="formFormatData.formData.channel.toutiao.tt_url" class="form-help">点击复制链接</p>
                            </el-form-item>
                             <el-form-item label="Token(令牌)"  v-if="formFormatData.formData.channel.toutiao.service=='5'">
                               <span style="margin-left:0;" class="pointer" v-if="formFormatData.formData.channel.toutiao.tt_token&&!isOpenEdit" @click="handleClipboard(formFormatData.formData.channel.toutiao.tt_token,$event)">{{formFormatData.formData.channel.toutiao.tt_token}}</span>
                                    <p v-if="formFormatData.formData.channel.toutiao.tt_token&&!isOpenEdit" class="form-help">点击复制链接</p>
                                     <div v-if="isOpenEdit" class="flex-row">
                                  <!-- v-model="formFormatData.formData.channel.toutiao.authorized.Token" -->
                                    <el-input maxlength="32" v-if="isOpenEdit" v-model="formFormatData.formData.channel.toutiao.tt_token"></el-input>
                                    <el-button style="margin-left:10px;" type="text" @click="setRandom(32,'tt_token')">随机生成</el-button>
                                </div>
                             </el-form-item>
                             <el-form-item label="商户号" prop="username"  v-if="formFormatData.formData.channel.toutiao.service=='5'">
                                  <span v-if="formFormatData.formData.channel.toutiao.tt_mch&&!isOpenEdit">{{formFormatData.formData.channel.toutiao.tt_mch}}</span>
                                   <div v-if="isOpenEdit">
                                      <el-input  v-model="formFormatData.formData.channel.toutiao.tt_mch" placeholder="请输入商户号"></el-input>
                                   </div>
                            </el-form-item>
                             <el-form-item label="SALT" prop="username"  v-if="formFormatData.formData.channel.toutiao.service=='5'">
                                 <span v-if="formFormatData.formData.channel.toutiao.tt_salt&&!isOpenEdit">{{formFormatData.formData.channel.toutiao.tt_salt}}</span>
                                   <div v-if="isOpenEdit">
                                        <el-input  v-model="formFormatData.formData.channel.toutiao.tt_salt" placeholder="请输入SALT"></el-input>
                                   </div>
                            </el-form-item>
                            
                             

                            
                  </el-form>
               </section>
        </div>
    </div>
    <div v-if="isOpenEdit" v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
        <el-button size="small" @click="saveForm" type="primary">保存</el-button>
        <el-button @click="isOpenEdit=false" size="small">取消</el-button>
    </div>
</div>
</template>

<script>
import {
  channelGet,
  channelSave
} from '@/api/channel'
import clipboard from '@/utils/clipboard'
import waves from '@/directive/waves' // Waves directive
import mixins from '@/mixins/mixins'
import exceldown from '@/directive/exceldown'
import ChooseFiles from '@/components/ChooseFiles/index'
import ChooseLink from '@/components/ChooseLink/index'
import { mapGetters } from 'vuex'

import Vue from 'vue'
import VueDND from 'awe-dnd'
Vue.use(VueDND)

export default {
  mixins: [mixins.getters('Form')],
  name: 'WeChatAppletsChannel',
  components: {
    ChooseFiles,
    ChooseLink
  },
  directives: {
    waves,
    exceldown
  },
  computed: {
    orga() {
      return window.location.origin
    },
    ...mapGetters([
      'independent'
    ]),
    isIndependent() {
      return this.$store.getters.independent
    }
  },
  created() {

  },
  data() {
    return {
      chooseFilesConfig: {
        type: ['image'],
        model: 'normal',
        initList: [],
        file_type: 'image'
      },
      chooseIconLinkConfig: {
        type: ['chooseLink'],
        initList: [],
        link_type: '1'
      },
      isOpenEdit: false,
      chooseLogoConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          model: 'display'
        },
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'channel|toutiao|logo',
          model: 'img'
          // validateField: 'merchantlog'
        }
      },
      chooseBgConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          isMore: true,
          model: 'display'
        },
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'channel|toutiao|qrcode',
          model: 'img'
          // validateField: 'businessbackgroundmap'
        }
      },
      formFormatData: {
        key: 'WeChatAppletsChannel',
        api: {
          editForm: {
            api: channelGet,
            params: {
              type: 'toutiao',
              always: true
            },
            filters: {
              img: {
                bindInit: ['chooseLogoConfig', 'chooseBgConfig']
              }
            }
          },
          submitForm: channelSave
        },
        autofocusType: 1,
        isOpendSetting: false,
        formData: {
          type: 'toutiao',
          channel: {
            toutiao: {
              authorized: { tt_token: ''},
              tt_token:'',
              tt_url:'',
              tt_mch:'',
              tt_salt:'',
              service:'1',
              video_entry:[],
              name: '',
              AppId: '',
              AppSecret: '',
              logo: [],
              qrcode: [],
              switch: '0',
              tt_bind_phone_type:'api',
              button: [],
              is_distribution:'2',
              is_membership:'2',
              is_together:'2',
            },
          },
         
         
        },
        rules: {

        }
      }
    }
  },
  watch: {
    'formFormatData.formData.channel.toutiao.button':{
      handler(val) {
        console.log('formFormatData 1211111',val)
      },
      deep: false
    }
  },
  methods: {
    setRandom(len, name) {
      len = len || 32
      var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      this.formFormatData.formData.channel.toutiao[`${name}`] = pwd
      console.log("|44444444444444",this.formFormatData.formData.channel.toutiao)
      console.log(pwd.length)
    },
    handleClipboard(text, event) {
      clipboard(text, event)
    },
    uploadChange({ displayData = [] }) {
      console.log(arguments, 'displayData22')
      this.$set( this.formFormatData.formData.channel.toutiao.button[this.$index],'image',1)
      this.formFormatData.formData.channel.toutiao.button[this.$index]['image'] = displayData[0]
      // this.formFormatCallBack()
    },
    uploadColumn(index) {
      console.log("55555555",this.$refs)
      this.$refs.chooseFilesIcon.toggle()
      this.$index = index
    },
    uploadFileToggle(index) {
      this.$index = index
      this.$refs.chooseIconLink.toggle()
    },
    uploadIconFileChange(files) {
      const { currentRow: [file_path] } = files
      if (file_path) {
        console.log(file_path, 'file_path')
        console.log(this.formFormatData.formData.channel.toutiao.button[this.$index], 'file_path22')
        this.formFormatData.formData.channel.toutiao.button[this.$index]['link'] = file_path
      } else {
        this.$message.error('请选择链接~!')
      }
    },
    saveForm() {
      this.formFormatSubmit()
      this.isOpenEdit = false
    },
    formFormatCallBack(data, type, response) {
      if (type === 'editForm') {
        const { data: { data: listData = [] } } = response
        console.log(response, '$listData')
        const isOpen = !Array.isArray(listData)
        //  || (Object.keys(listData)[0] === 'switch' && Object.keys(listData)['length'] === 0)
        this.formFormatData.isOpendSetting = isOpen
        //回显给默认值
        if(!response.data.data.channel.toutiao.video_entry){
          //处理接口请求回来没video_entry这个字段，并且触发响应式
          this.$set(this.formFormatData.formData.channel.toutiao,'video_entry',[])
        }
        if(!response.data.data.channel.toutiao.tt_bind_phone_type){
          this.formFormatData.formData.channel.toutiao.tt_bind_phone_type = 'api'
        }
        //新增商品详情左下角操作设置，
        //构造商品详情左下角操作设置数据
        let buttondata =[
          {
          input: "",
          link: "",
          title: "首页",
          type: "1",
          image:{
          }
        },
        {
          input: "",
          link: "",
          title: "分享",
          type: "1",
          image:{
            
          }
        },
        {
          input: "",
          link: "",
          title: "订单",
          type: "1",
          image:{
          }
        },
        ]
     
        if(!response.data.data.channel.toutiao.button){
           this.$set(this.formFormatData.formData.channel.toutiao,'button',buttondata)
        }
        if(!response.data.data.channel.toutiao.button.image){
          this.$set(this.formFormatData.formData.channel.toutiao.button,'image',buttondata.image)
        }
        // is_distribution:'2',
        //       is_membership:'2',
        //       is_together:'2',
        if(!response.data.data.channel.toutiao.is_distribution || !response.data.data.channel.toutiao.is_membership|| !response.data.data.channel.toutiao.is_together){
           this.$set(this.formFormatData.formData.channel.toutiao,'is_distribution','2')
           this.$set(this.formFormatData.formData.channel.toutiao,'is_membership','2')
           this.$set(this.formFormatData.formData.channel.toutiao,'is_together','2')
        }
      }
    },
    open() {
      this.isOpenEdit = true
      // this.$alert('是否需要绑定其它头条小程序？', '通知', {
      //   showCancelButton: true,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   callback: action => {
      //     if (action === 'confirm') {
      //       this.$router.push({
      //         path: '/channel/toutiaoAppletsChannelAdd?'
      //       })
      //     }
      //   }
      // })
    },
    switchChannel() {
      if (this.formFormatData.isOpendSetting) {
        channelSave(this.formFormatData.formData).then((res) => {
          const { data: { code } } = res
          if (code === 0) {
            this.$message.success('保存成功！~')
          }
        })
      } else {
        this.$message.error('请先接入头条公众号再开启！~')
        this.formFormatData.formData.channel.toutiao.switch = '0'
      }
    }
  }
}
</script>
<style lang="scss" scoped>
$update: 50px;
.fileItem {
    height: 66px;
    margin-bottom: 20px;
    border: 1px solid #ddd;
    font-size: 14px;
    border-radius: 3px;

    .fileName {
      text-align: right;
      width: 170px;
      padding-right: 20px;
      line-height: 60px;
    }
  }
.fileItemHeader {
    height: 66px;
    margin-bottom: 20px;
    text-align: center;
    border-bottom: 1px solid #ddd;
    font-size: 14px;

    .icon {
      margin-left: 170px;
      width: 50px;
    }

    .text {
      margin-left: 16px;
      width: 270px;
    }

    .link {
      margin-left: 16px;
      width: 290px;
    }
  }

  .update-load {
    display: inline-block;
    cursor: pointer;
    width: $update;
    height: $update;
    background: #fafbff;
    border: 1px dashed #c0ccda;
    color: #a8abb0;
    border-radius: 5px;

    i {
      font-size: 14px;
      color: #8c939d;
      width: $update;
      height: $update;
      line-height: $update;
      text-align: center;
    }
  }

  .link-box {
    margin-left: 20px;
    background: #e8effc;
    border: 0;
    width: 290px;
    height: 28px;
    line-height: 28px;
    border-radius: 3px;
    padding-left: 18px;
    cursor: pointer;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
</style>
